# -*- coding:utf-8 -*-

from contextlib import asynccontextmanager
from fastapi import FastAPI
from tortoise import Tortoise
from config import settings

def getenv(key, default=None):
    return settings.dict()[key] if key in settings.dict() else default

# -----------------------数据库配置-----------------------------------
DB_ORM_CONFIG = {
    "connections": {
        "default": {
            'engine': 'tortoise.backends.mysql',
            "credentials": {
                'host': getenv('DB_HOST', '127.0.0.1'),
                'port': int(getenv('DB_PORT', 3306)),
                'user': getenv('DB_USER', 'root'),
                'password': getenv('DB_PASSWORD', '123456'),
                'database': getenv('DB_NAME', 'base'),
                'minsize': 1,
                'maxsize': 5,
                'charset': 'utf8mb4',
                'echo': True,
            }
        },
    },
    "apps": {
        "models": {"models": ["models.base"], "default_connection": "default"},
    },
    'use_tz': False,
    'timezone': 'Asia/Shanghai'
}


# async def register_mysql(app: FastAPI):
#     # 注册数据库
#     await Tortoise.init(config=DB_ORM_CONFIG)

@asynccontextmanager
async def register_mysql(app: FastAPI):
    try:
        async with RegisterTortoise(
            app,
            config=TORTOISES_CONFIG,
        ):
            yield print("mysql connected")
            await connections.close_all()
            print("mysql closed")
    except Exception as e:
        print(e)